import * as FS from 'node:fs/promises'
import * as Path from 'node:path'
// TODO: Fix vite dependency issue
// import type { Plugin } from 'vite'
import { discoverExamples } from './discovery.js'
import type { ExamplesPluginConfig } from './types.js'

/**
 * Vite plugin that discovers example files and generates TypeScript types.
 * The generated types provide type-safe references to example file paths.
 */
export const examplesPlugin = (config: ExamplesPluginConfig = {}): any => {
  const typeGenConfig = config.typeGeneration ?? {}
  const enabled = typeGenConfig.enabled ?? true
  const outputDir = typeGenConfig.outputDir ?? 'node_modules/@generated/test-examples'
  const packageName = typeGenConfig.packageName ?? '@generated/test-examples'
  const outputFile = `${outputDir}/types.d.ts`
  const packageJsonFile = `${outputDir}/package.json`

  return {
    name: 'vitest-plugin-examples',

    async buildStart() {
      if (!enabled) return

      // Discover examples
      const examples = await discoverExamples(config)

      // Generate interface with example paths
      const interfaceContent = examples
        .map((ex) => `  '${ex.relativePath}': true`)
        .join('\n')

      const content = `// Auto-generated by vitest-plugin-examples
// Do not edit manually

/**
 * Map of all discovered example file paths.
 * Use \`ExamplePath\` type for type-safe references to example files.
 */
export interface ExampleFiles {
${interfaceContent}
}

/**
 * Union type of all example file paths.
 * Use this for type-safe encoder configuration and example references.
 */
export type ExamplePath = keyof ExampleFiles
`

      // Create package.json to make it a proper npm package
      const packageJson = {
        name: packageName,
        version: '0.0.0',
        private: true,
        types: './types.d.ts',
      }

      // Write generated files
      await FS.mkdir(Path.dirname(outputFile), { recursive: true })
      await FS.writeFile(outputFile, content, 'utf8')
      await FS.writeFile(packageJsonFile, JSON.stringify(packageJson, null, 2), 'utf8')

      console.log(`[vitest-plugin-examples] Generated types for ${examples.length} examples`)
    },
  }
}
